package com.example.leo.mycharmingstudent.project.maintabfragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.leo.mycharmingstudent.R;
import com.example.leo.mycharmingstudent.a0905.ToastUtil;
import com.example.leo.mycharmingstudent.a0917.practice.HandlerUtil;
import com.example.leo.mycharmingstudent.project.MainActivity;
import com.example.leo.mycharmingstudent.project.SubPageActivity;
import com.example.leo.mycharmingstudent.project.adapter.KnowledgeAdapter;
import com.example.leo.mycharmingstudent.project.constant.ApiInterface;
import com.example.leo.mycharmingstudent.project.entity.KnowledgeTreeEntity;
import com.example.leo.mycharmingstudent.project.util.OkHttpUtil;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by Leo on 2020/9/28.
 */

public class KnowledgeFragment extends Fragment {

    //知识体系列表
    private RecyclerView rvKnowledge;

    //知识体系条目数据列表
    private List<KnowledgeTreeEntity.DataBean> mKnowledgeList = new ArrayList<>();
    private KnowledgeAdapter mKnowledgeAdapter;
    private SwipeRefreshLayout srlKnowledge;

    public static KnowledgeFragment newInstance() {
        KnowledgeFragment knowledgeFragment = new KnowledgeFragment();
        return knowledgeFragment;
    }

    /**
     * 呈现给用户最美好的一面
     * 通俗来讲，叫创建View
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_knowledge, container, false);
        rvKnowledge = inflate.findViewById(R.id.rv_fragment_knowledge);
        srlKnowledge = inflate.findViewById(R.id.srl_fragment_knowledge);
        return inflate;
    }

    /**
     * 初始化数据,例如网络请求
     *
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        initEvent();
    }

    private void initData() {
        //getContext方法，在onActivityCreated生命周期方法之后，才一定不为null
        rvKnowledge.setLayoutManager(new LinearLayoutManager(getContext()));
        /*
        new关键字 创建对象
        对象哪里去了？都在内存里
        如何找到他或她（对象）?用变量就能从内存中，一眼找到他或她。
        此处的变量指的是mKnowledgeAdapter
        此处的对象指的是new KnowledgeAdapter
         */
        mKnowledgeAdapter = new KnowledgeAdapter(getContext(), mKnowledgeList);
        rvKnowledge.setAdapter(mKnowledgeAdapter);

        KnowledgeAdapter.OnKnowledgeItemClickListener onKnowledgeItemClickListener =
                new KnowledgeAdapter.OnKnowledgeItemClickListener() {
                    @Override
                    public void onItemClick(int position, KnowledgeTreeEntity.DataBean dataBean) {
                        String name = dataBean.getName();
                        ToastUtil.showToast(getContext(), name);
                        SubPageActivity.startSubPageActivity(
                                getContext(),
                                name,
                                dataBean.getChildren()
                        );
                    }
                };
        mKnowledgeAdapter.setOnKnowledgeItemClickListener(onKnowledgeItemClickListener);

        requestKnowledge();
    }

    /**
     * 请求知识体系接口
     * https://www.wanandroid.com/tree/json
     */
    private void requestKnowledge() {
        OkHttpUtil.enqueue(ApiInterface.KNOWLEDGE_URL, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Gson gson = new Gson();
                KnowledgeTreeEntity knowledgeTreeEntity = gson.fromJson(result, KnowledgeTreeEntity.class);
                if (knowledgeTreeEntity.getErrorCode() == 0) {
                    mKnowledgeList.clear();
                    mKnowledgeList.addAll(knowledgeTreeEntity.getData());
                    HandlerUtil.post(new Runnable() {
                        @Override
                        public void run() {
                            srlKnowledge.setRefreshing(false);
                            mKnowledgeAdapter.notifyDataSetChanged();
                        }
                    });
                }
            }
        });
    }

    /**
     * 初始化事件的操作，例如点击事件，滚动事件等
     * 不唯一，可以有自己的写法
     */
    private void initEvent() {
        srlKnowledge.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestKnowledge();
            }
        });
    }
}
